<?php
declare(strict_types=1);

namespace Hyperfx\Framework\Redis\Lock;

use Hyperf\Config\Config;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use Lysice\HyperfRedisLock\RedisLock;


/**
 * @method get($callback = null)
 * @method block($seconds, $callback = null)
 * @method release()
 * @method acquire(): bool
 * @method owner()
 * @method forceRelease()
 */
class BaseLock {

    private RedisLock $redisLock;

    public function step(array $params)
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(RedisFactory::class)->get($this->instance);

        // 解析KEY
        $this->parserKey($params);

        $this->redisLock = new RedisLock($redis, $this->key, $this->seconds);
    }

    public function getSeconds(): int {
        return $this->seconds;
    }

    /**
     * 解析key
     */
    private function parserKey(array $params) {
        $prefix = Config(sprintf('redis.%s.prefix', $this->instance), Config('app_name'));

        $key = sprintf($this->key, ...$params);
        $this->key = sprintf(
            '%s:lock:%s',
            $prefix,
            $key
        );
//        $search = [];
//        $replace = [];
//        foreach ($params as $key => $val) {
//            $search[] = sprintf('${%s}', $key);
//            $replace[] = $val;
//        }
//        $replaced = str_replace($search, $replace, $this->key);
//        $this->key = sprintf('%s:lock:%s', Config('app_name'), $replaced);
    }

    public function getKey(): string {
        return $this->key;
    }

    public function __call($name, $arguments)
    {
        return $this->redisLock->{$name}(...$arguments);
    }
}